<template>
  <view>
    <view class="font-24 color-808080 m-30" @click="copyText(roomId)">房间号：{{roomId}}</view>
    <view>
      <view class="font-24 color-808080 m-x-30">当前房间人数：{{userList.length}}</view>
      <view class="flex align-center ">
          <view v-for="item in userList" class="bg-white p-20 m-20 radius-16 flex flex-column align-center">
            <uv-avatar :src="item.avatar"/>
            <view class="font-28 m-y-4">{{item.name}}</view>
            <view class="font-24 color-808080">编号：{{item.id}}</view>
          </view>
      </view>
    </view>
    <scroll-view class="chat-container" scroll-y>
      <block v-for="(msg, index) in messages" :key="index">
        <view class="time">{{ transformTime(msg.sentTime) }}</view>
        <view class="message" :class="{ 'self': msg.messageDirection == 1}">
          <view class="context">
            <image :src="msg.messageDirection == 1 ? myInfo.avatar : msg.content.user.avatar" style="width: 80rpx;height:80rpx;border-radius: 16rpx"/>
            <view class="content">{{ msg.content.content }}</view>
          </view>
        </view>
      </block>
    </scroll-view>
    <view class="input-area border-top">
      <input type="text" placeholder="输入消息..." v-model="inputMsg" @confirm="sendMessage" class="border"/>
      <button @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
 import * as RongIMLib from '@rongcloud/imlib-next'
 import {onLoad} from "@dcloudio/uni-app";
 import {ref} from "vue";
 import {copyText, transformTime} from "@/utils/utils";
 import tips from "@/utils/tips";
 import {Events} from "@rongcloud/imlib-next";
 import {loginApi} from "@/api";

 const roomId = ref('') // 房间号
 const inputMsg = ref(''); // 输入框内容
 const messages = ref([]); // 模拟的聊天消息
 const myInfo = ref(uni.getStorageSync('user')) // 当前用户信息
 const userList = ref([]) // 当前房间用户列表

 // 创建聊天室
 const createRoom = () => {
   const chatRoomId = String(Date.now());
   const count = 50;

   RongIMLib.joinChatRoom(chatRoomId, {
     count: count
   }).then(res => {
     // 加入聊天室成功
     if (res.code === RongIMLib.ErrorCode.SUCCESS){
       console.log(res.code)
       roomId.value = chatRoomId
       getRoomInfo()
       tips.showToast('创建成功')
     } else {
       console.log(res.code, res.msg)
     }
   }).catch(error => {
     console.log(error)
   })
 }

 // 加入聊天室
 const joinRoom = () => {
   const count = 50;

   RongIMLib.joinExistChatRoom(roomId.value, {
     count: count
   }).then(res => {
     // 加入聊天室成功
     const { code, data } = res;
     if(code === RongIMLib.ErrorCode.SUCCESS){
       tips.showToast('成功加入房间')
       console.log(code, data)
       getHistoryMessage()
       getRoomInfo()
     } else {
       console.log(code)
     }
   }).catch(error => {
     console.log(error)
   })
 }

 // 获取房间信息
 const getRoomInfo = () => {
   const count = 10 // 获取房间人员列表数量，最大有效值 `20`，最小值为 `0`，默认为 0
   const order = 1 // 人员排序方式，`1` 为正序，`2` 为倒序，默认为 0
   RongIMLib.getChatRoomInfo(roomId.value, {
     count: count,
     order: order
   }).then(async res => {
     // 获取聊天室信息成功
     if(res.code === 0){
       let ids = res.data.userInfos.map(item => item.id).join(',')
       let result = await loginApi.getUserInfoByIds({ids})
       userList.value = result.data
       console.log('获取房间信息成功', result.data)

     } else {
       console.log(res.code, res.data)
     }
   })
 }

 // 监听聊天室事件
 const listener = (event) => {
   if (event.rejoinedRoom) {
     console.log('SDK 内部重连聊天室信息:', event.rejoinedRoom)
   }
   if (event.updatedEntries) {
     console.log('监听到的聊天室 KV 更新:', event.updatedEntries)
   }
   if (event.userChange) {
     console.log('加入退出的用户通知:', event.userChange)
   }
   if (event.chatroomDestroyed) {
     console.log('聊天室销毁:', event.chatroomDestroyed)
   }
   /*  since 5.7.9 */
   if (event.chatroomNotifyMultiLoginSync) {
     console.log('加入退出多端同步通知:', event.chatroomNotifyMultiLoginSync)
   }
   /*  since 5.7.9 */
   if (event.chatroomNotifyBlock) {
     console.log('聊天室用户封禁通知:', event.chatroomNotifyBlock)
   }
   /*  since 5.7.9 */
   if (event.chatroomNotifyBan) {
     console.log('聊天室用户禁言通知:', event.chatroomNotifyBan)
   }
 }

 // 获取聊天室历史信息
 const getHistoryMessage = () => {
   const chatRoomId = roomId.value;
   const timestamp = 0;
   const count = 10
   const order = 0
   RongIMLib.getChatroomHistoryMessages(chatRoomId, {
     timestamp: timestamp,
     count: count,
     order: order
   }).then(res => {
     // 获取聊天室历史信息成功
     if (res.code === 0){
       console.log(res.code, res.data)
       messages.value = messages.value.concat(res.data.list)
     } else {
       console.log(res.code, res.msg)
     }
   }).catch(error => {
     console.log(error)
   })
 }

 // 发送消息
 const sendMessage = () => {
   if (inputMsg.value.trim() == '') return
   // 指定消息发送的目标会话
   let conversation = {
     targetId: roomId.value, // targetId
     conversationType: RongIMLib.ConversationType.CHATROOM // 会话类型：RongIMLib.ConversationType.PRIVATE | RongIMLib.ConversationType.GROUP
   };

   // 构建文本消息
   const message = new RongIMLib.TextMessage({
     content: inputMsg.value,
     user : uni.getStorageSync('user'),
   })
   inputMsg.value = ''; // 清空输入框

// 发送消息
   console.log('消息发送：', conversation)

   RongIMLib.sendMessage(conversation, message).then(({ code, data }) => {
     if (code === 0) {
       messages.value.unshift(data)
       console.log('消息发送成功：', data)
     } else {
       console.log('消息发送失败：', code)
     }
   });
 }

 onLoad((option)=>{
   roomId.value = option.id || ''
   option.id ? joinRoom() : createRoom()
   RongIMLib.addEventListener(Events.CHATROOM, listener)

   uni.$on('receiveMessage', (data) => {
     console.log('data', data)
     if (data.targetId == roomId.value){
        messages.value.unshift(data)
     }
   })
 })
</script>

<style scoped lang="scss">
.chat-container{
  height: 800rpx;
}
.message {
  margin: 10rpx 0;
  padding: 10px;
  border-radius: 10px;
  &.self{
    align-self: flex-end;
    .context{
      flex-direction: row-reverse;
      .content{
        background-color: #b3e5fc;
      }
    }
  }
  &:not(.self) {
    align-self: flex-start;
    .context{
      flex-direction: row;
      .content{
        background-color: #e0e0e0;
      }
    }
  }
  .context{
    display: flex;
    align-items: center;
    .content{
      max-width: 70%;
      margin: 0 20rpx;
      display: flex;
      align-items: center;
      padding: 10rpx;
      border-radius: 10rpx;
    }
    .tip{
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }
}

.time {
  text-align: center;
  font-size: 12px;
  color: #999;
}

.input-area {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  padding: 10px;
  background-color: #fff;
  box-sizing: border-box;
}

.input-area input {
  flex: 1;
  height: 40px;
  padding: 0 10px;
}

.input-area button {
  height: 40px;
  margin-left: 10px;
}
</style>
